//
//  AMAlertHelper.m
//  Silent
//QrCode
//  Created by chabao on 2018/4/24.
//

#import "QRCodePlugin.h"
#import "MKQRCode.h"

#import <UIKit/UIKit.h>

@implementation QRCodePlugin

-(void)createQRCodeImage:(CDVInvokedUrlCommand *)command{
    // 模拟H5传来的base64图片字符串
//    UIImage *images = [UIImage imageNamed:@"feng"];
//    NSData *datas = UIImageJPEGRepresentation(images, 2.0f);
//    NSString *encodedImageStrs = [datas base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//    NSData *decodedImageData = [[NSData alloc] initWithBase64EncodedString:encodedImageStrs options:NSDataBase64DecodingIgnoreUnknownCharacters];
//    UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
//
    __weak QRCodePlugin *weakSelf = self;
    [self.commandDelegate runInBackground:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [self richScanQRCode];
            NSData *data = UIImageJPEGRepresentation(image, 1.0f);
            NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            
            NSDictionary *dict = @{
                                   @"code": @0,
                                   @"qrcodeByte": encodedImageStr
                                   };
            NSString *reStr = [self toJSONData:dict];
            CDVPluginResult *pluginResult = nil;
            if (encodedImageStr) {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:reStr];
                [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            }
        });
    }];
}

- (NSString*)toJSONData:(id)theData{
    NSString* jsonString = @"";
    if(theData != nil) {
        NSData*jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                         options:NSJSONWritingPrettyPrinted
                                                           error:nil];
        
        if([jsonData length] != 0){
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
    }
    return jsonString;
}

- (UIImage *)richScanQRCode {
    MKQRCode *code = [[MKQRCode alloc] init];
    [code setInfo:@"嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿嘿" withSize:300];
    code.centerImg = [UIImage imageNamed:@"feng"];
    code.style = MKQRCodeStyleCenterImage;
    return [code generateImage];
}
@end
